import React, {useState, useEffect} from 'react';
import {Button, Modal, Steps} from 'antd';
import styles from './styles/index.module.less';
import OrderConfirm from './OrderConfirm';
import PaymentMethod from './PaymentMethod';
import PaymentResult from './PaymentResult';
import CashPayment from "@/components/PaymentModal/CashPayment";
import DateUtil from "@/utils/DateUtils";
import {updateOrderInfoById} from "@/pages/order/order-edit/api";
import {API} from "@/services/typings";

const {Step} = Steps;

interface PaymentModalProps {
  visible: boolean;
  orders: API.IOrderInfo[];
  onCancel: () => void;
  onSuccess: () => void;
}

const PaymentModal: React.FC<PaymentModalProps> = ({visible, orders, onCancel, onSuccess}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [paymentMethod, setPaymentMethod] = useState<string>('');
  const [paymentResult, setPaymentResult] = useState<boolean | null>(null);
  const [cashPaymentVisible, setCashPaymentVisible] = useState(false)
  const [loading, setLoading] = useState(false);

  const totalAmount = orders.reduce((sum, order) => sum + (order.paidAmount || 0), 0);

  // 现金支付
  const handleCashPay = async () => {
    for (let order of orders) {
      order.settlementType = '3' // 结款类型为下单支付
      order.payMethod = '3'  // 现金支付
      order.paidStatus = '1'
      order.paidTime = DateUtil.getNowTime()
      await updateOrderInfoById(order)
    }
    setCurrentStep(2)
    setCashPaymentVisible(false)
    setPaymentResult(true)
    onSuccess?.()
  };

  const handleMethodChange = (method: string) => {
    console.log("method", method)
    setPaymentMethod(method);
    if (method === 'cash') {
      setCashPaymentVisible(true)
    }
  };


  const steps = [
    {title: '订单确认'},
    {title: '支付方式'},
    {title: '支付结果'},
  ];

  useEffect(() => {
    if (!visible) {
      setCurrentStep(0);
      setPaymentMethod('0');
      setPaymentResult(null);
    }
  }, [visible]);


  return (
    <Modal
      title="订单支付"
      visible={visible}
      onCancel={onCancel}
      footer={null}
      width={840}
      bodyStyle={{padding: '24px 0'}}
      centered
      destroyOnClose
      className={styles.modal}
    >
      <Steps current={currentStep} className={styles.steps}>
        {steps.map((item, index) => (
          <Step key={index} title={item.title}/>
        ))}
      </Steps>

      <div className={styles.content}>
        {currentStep === 0 && (
          <OrderConfirm
            orders={orders}
            totalAmount={totalAmount}
            onChoosePayment={() => {
              setCurrentStep(1)
            }}
          />
        )}
        {currentStep === 1 && (
          <PaymentMethod
            onChange={handleMethodChange}
            totalAmount={totalAmount}
            onBackOrder={() => {
              setCurrentStep(0)
            }}
            paymentMethod={paymentMethod}/>
        )}
        {currentStep === 2 && paymentResult !== null && (
          <PaymentResult
            success={paymentResult}
            orders={orders}
            totalAmount={totalAmount}
          />
        )}
      </div>
      <CashPayment
        visible={cashPaymentVisible}
        amount={totalAmount}
        loading={loading}
        onOk={handleCashPay}
        onCancel={() => {
          setPaymentMethod('')
          setCashPaymentVisible(false)
        }}
      />
    </Modal>
  );
};

export default PaymentModal;
